import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../models/expense_model.dart';
import '../providers/expense_providers.dart';
import '../themes/expense_theme.dart';
import 'add_expense_screen.dart';
import 'expense_statistics_screen.dart';

/// 记账应用主界面
class ExpenseHomeScreen extends ConsumerWidget {
  const ExpenseHomeScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final currentMonthIncome = ref.watch(currentMonthIncomeProvider);
    final currentMonthExpense = ref.watch(currentMonthExpenseProvider);
    final currentMonthNet = ref.watch(currentMonthNetIncomeProvider);
    final recentExpenses = ref.watch(recentExpensesProvider);

    return Scaffold(
      backgroundColor: ExpenseTheme.background,
      appBar: AppBar(
        title: const Text('我的记账本'),
        backgroundColor: ExpenseTheme.primaryBlue,
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.bar_chart),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const ExpenseStatisticsScreen(),
                ),
              );
            },
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          ref.read(expenseListProvider.notifier).loadExpenses();
        },
        color: ExpenseTheme.primaryBlue,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: EdgeInsets.all(16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 当月概览卡片
              _buildEnhancedMonthlyOverviewCard(
                context,
                currentMonthIncome,
                currentMonthExpense,
                currentMonthNet,
              ),

              SizedBox(height: 24.h),

              // 快速操作按钮
              _buildEnhancedQuickActionButtons(context),

              SizedBox(height: 24.h),

              // 最近记录标题
              _buildSectionHeader('最近记录', Icons.history),

              SizedBox(height: 16.h),

              // 最近记录列表
              _buildEnhancedRecentExpensesList(context, recentExpenses),
            ],
          ),
        ),
      ),
      floatingActionButton: Container(
        decoration: BoxDecoration(
          gradient: ExpenseTheme.primaryGradient,
          borderRadius: BorderRadius.circular(28.r),
          boxShadow: [
            BoxShadow(
              color: ExpenseTheme.primaryBlue.withValues(alpha: 0.3),
              blurRadius: 12,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: FloatingActionButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const AddExpenseScreen()),
            );
          },
          backgroundColor: Colors.transparent,
          elevation: 0,
          child: const Icon(Icons.add, color: Colors.white, size: 28),
        ),
      ),
    );
  }

  /// 构建增强的当月概览卡片
  Widget _buildEnhancedMonthlyOverviewCard(
    BuildContext context,
    double income,
    double expense,
    double net,
  ) {
    final now = DateTime.now();
    final monthName = DateFormat('yyyy年MM月', 'zh_CN').format(now);

    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        gradient: ExpenseTheme.primaryGradient,
        borderRadius: BorderRadius.circular(24.r),
        boxShadow: [
          BoxShadow(
            color: ExpenseTheme.primaryBlue.withValues(alpha: 0.3),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Stack(
        children: [
          // 背景装饰
          Positioned(
            top: -20,
            right: -20,
            child: Container(
              width: 100.w,
              height: 100.h,
              decoration: BoxDecoration(
                color: Colors.white.withValues(alpha: 0.1),
                shape: BoxShape.circle,
              ),
            ),
          ),
          Positioned(
            bottom: -30,
            left: -30,
            child: Container(
              width: 80.w,
              height: 80.h,
              decoration: BoxDecoration(
                color: Colors.white.withValues(alpha: 0.05),
                shape: BoxShape.circle,
              ),
            ),
          ),
          // 内容
          Padding(
            padding: EdgeInsets.all(24.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(
                      Icons.calendar_month,
                      color: Colors.white,
                      size: 20.sp,
                    ),
                    SizedBox(width: 8.w),
                    Text(
                      monthName,
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20.h),

                // 净收入
                Text(
                  '净收入',
                  style: TextStyle(fontSize: 14.sp, color: Colors.white70),
                ),
                SizedBox(height: 8.h),
                Text(
                  '¥${net.toStringAsFixed(2)}',
                  style: TextStyle(
                    fontSize: 36.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),

                SizedBox(height: 24.h),

                // 收入和支出
                Row(
                  children: [
                    Expanded(
                      child: _buildEnhancedAmountItem(
                        '收入',
                        income,
                        ExpenseTheme.mintGreen,
                        Icons.trending_up,
                      ),
                    ),
                    SizedBox(width: 16.w),
                    Expanded(
                      child: _buildEnhancedAmountItem(
                        '支出',
                        expense,
                        ExpenseTheme.pinkAccent,
                        Icons.trending_down,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建增强的金额项目
  Widget _buildEnhancedAmountItem(
    String label,
    double amount,
    Color color,
    IconData icon,
  ) {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.15),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(
          color: Colors.white.withValues(alpha: 0.2),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: EdgeInsets.all(6.w),
                decoration: BoxDecoration(
                  color: color.withValues(alpha: 0.2),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Icon(icon, color: color, size: 16.sp),
              ),
              SizedBox(width: 8.w),
              Text(
                label,
                style: TextStyle(fontSize: 12.sp, color: Colors.white70),
              ),
            ],
          ),
          SizedBox(height: 8.h),
          Text(
            '¥${amount.toStringAsFixed(2)}',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建节标题
  Widget _buildSectionHeader(String title, IconData icon) {
    return Row(
      children: [
        Container(
          padding: EdgeInsets.all(8.w),
          decoration: BoxDecoration(
            color: ExpenseTheme.primaryBlue.withValues(alpha: 0.1),
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Icon(icon, color: ExpenseTheme.primaryBlue, size: 20.sp),
        ),
        SizedBox(width: 12.w),
        Text(
          title,
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: ExpenseTheme.textPrimary,
          ),
        ),
      ],
    );
  }

  /// 构建增强的快速操作按钮
  Widget _buildEnhancedQuickActionButtons(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(20.r),
        boxShadow: ExpenseTheme.cardShadow,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.flash_on,
                color: ExpenseTheme.primaryBlue,
                size: 20.sp,
              ),
              SizedBox(width: 8.w),
              Text(
                '快速操作',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                  color: ExpenseTheme.textPrimary,
                ),
              ),
            ],
          ),
          SizedBox(height: 16.h),
          Row(
            children: [
              Expanded(
                child: _buildEnhancedActionButton(
                  '收入记账',
                  Icons.trending_up,
                  ExpenseTheme.incomeGreen,
                  () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const AddExpenseScreen(
                          initialType: ExpenseType.income,
                        ),
                      ),
                    );
                  },
                ),
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: _buildEnhancedActionButton(
                  '支出记账',
                  Icons.trending_down,
                  ExpenseTheme.expenseRed,
                  () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const AddExpenseScreen(
                          initialType: ExpenseType.expense,
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建增强的操作按钮
  Widget _buildEnhancedActionButton(
    String label,
    IconData icon,
    Color color,
    VoidCallback onTap,
  ) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(16.r),
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 12.w),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              color.withValues(alpha: 0.1),
              color.withValues(alpha: 0.05),
            ],
          ),
          borderRadius: BorderRadius.circular(16.r),
          border: Border.all(color: color.withValues(alpha: 0.3), width: 1),
        ),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.all(12.w),
              decoration: BoxDecoration(
                color: color.withValues(alpha: 0.1),
                shape: BoxShape.circle,
              ),
              child: Icon(icon, color: color, size: 24.sp),
            ),
            SizedBox(height: 8.h),
            Text(
              label,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: color,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建增强的最近记录列表
  Widget _buildEnhancedRecentExpensesList(
    BuildContext context,
    List<ExpenseModel> expenses,
  ) {
    if (expenses.isEmpty) {
      return Container(
        padding: EdgeInsets.all(40.w),
        decoration: BoxDecoration(
          color: ExpenseTheme.cardBackground,
          borderRadius: BorderRadius.circular(20.r),
          boxShadow: ExpenseTheme.softShadow,
        ),
        child: Column(
          children: [
            Icon(
              Icons.receipt_long,
              size: 48.sp,
              color: ExpenseTheme.textLight,
            ),
            SizedBox(height: 16.h),
            Text(
              '暂无记录',
              style: TextStyle(
                fontSize: 16.sp,
                color: ExpenseTheme.textSecondary,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              '点击右下角按钮开始记账',
              style: TextStyle(fontSize: 14.sp, color: ExpenseTheme.textLight),
            ),
          ],
        ),
      );
    }

    return Container(
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(20.r),
        boxShadow: ExpenseTheme.cardShadow,
      ),
      child: ListView.separated(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: expenses.length,
        separatorBuilder: (context, index) => Divider(
          height: 1,
          color: ExpenseTheme.divider,
          indent: 16.w,
          endIndent: 16.w,
        ),
        itemBuilder: (context, index) {
          final expense = expenses[index];
          return _buildEnhancedExpenseItem(context, expense);
        },
      ),
    );
  }

  /// 构建增强的记账项目
  Widget _buildEnhancedExpenseItem(BuildContext context, ExpenseModel expense) {
    final isIncome = expense.type == ExpenseType.income;
    final color = isIncome ? ExpenseTheme.incomeGreen : ExpenseTheme.expenseRed;
    final icon = isIncome ? Icons.trending_up : Icons.trending_down;

    return InkWell(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => AddExpenseScreen(expense: expense),
          ),
        );
      },
      child: Container(
        padding: EdgeInsets.all(16.w),
        child: Row(
          children: [
            Container(
              padding: EdgeInsets.all(12.w),
              decoration: BoxDecoration(
                color: color.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Text(
                expense.category.icon,
                style: TextStyle(fontSize: 20.sp),
              ),
            ),
            SizedBox(width: 16.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
                        expense.category.displayName,
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                          color: ExpenseTheme.textPrimary,
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Icon(icon, size: 16.sp, color: color),
                    ],
                  ),
                  if (expense.description.isNotEmpty) ...[
                    SizedBox(height: 4.h),
                    Text(
                      expense.description,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: ExpenseTheme.textSecondary,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                  SizedBox(height: 4.h),
                  Text(
                    DateFormat('MM月dd日 HH:mm', 'zh_CN').format(expense.date),
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: ExpenseTheme.textLight,
                    ),
                  ),
                ],
              ),
            ),
            Text(
              '${isIncome ? '+' : '-'}¥${expense.amount.toStringAsFixed(2)}',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
                color: color,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
